package hot100;

import java.util.HashMap;
import java.util.Map;

public class AddTwoNumbers {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p = l1;
        ListNode q = l2;

        int extra = 0;
        ListNode tail = null;
        while (p != null && q != null) {
            int plusRes = p.val + q.val + extra;
            int curVal = plusRes % 10;
            extra = plusRes / 10;
            p.val = curVal;
            tail = p;
            p = p.next;
            q = q.next;
        }

        while (p != null) {
            int plusRes = p.val + extra;
            int curVal = plusRes % 10;
            extra = plusRes / 10;
            p.val = curVal;
            tail = p;
            p = p.next;
        }

        while (q != null) {
            int plusRes = q.val + extra;
            int curVal = plusRes % 10;
            extra = plusRes / 10;
            q.val = curVal;
            tail.next = q;
            tail = q;
            q = q.next;
        }

        if (extra > 0) {
            ListNode node = new ListNode(extra);
            tail.next = node;
            tail = node;
        }

        return l1;
    }
}
